<template>
  <div class="layout">
    <el-upload
      style="display: inline-block; margin-right: 10px"
      name="files"
      :file-list="fileList"
      action="/api/upload/files"
      :multiple="true"
      :show-file-list="showList"
      :limit="limit"
      :on-error="fileError"
      :on-remove="fileRemove"
      :headers="headers"
      :auto-upload="false"
      :on-change="changeFiles"
    >
      <el-button v-if="slotValue" type="primary">
        {{ name }}
        <i class="el-icon-upload el-icon--right"></i
      ></el-button>
    </el-upload>
    <el-button class="button" v-if="slotValue" type="success" @click="submit()"
      >确认提交</el-button
    >
  </div>
</template>
<style scoped>
.layout {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  position: relative;
  width: 100%;
}
.button {
  position: absolute;
  right: 0;
}
</style>
<script setup>
import { ref, defineProps, defineEmits } from "vue";
import { Notification } from "element-ui";
import { upload } from "@/api/upload/index";
import store from "@/store";
const emit = defineEmits(["fileRemove", "filePush"]);
const slotValue = ref(true);
const resList = ref([]);
const headers = {
  Authorization: store.state.token,
};
const changeFiles = (file, files) => {
  resList.value = files;
};
const submit = async () => {
  let formData = new FormData();
  resList.value.forEach((e) => {
    formData.append("files", e.raw);
  });
  let res = await upload(formData);
  if (res.code == 0) {
    Notification({
      title: "成功",
      message: "文件上传成功",
      type: "success",
    });
    emit("filePush", res.data);
  } else {
    Notification({
      title: "失败",
      message: "文件上传失败",
      type: "error",
    });
  }
};
const props = defineProps({
  limit: {
    type: Number,
    default: () => 2,
  },
  showList: {
    type: Boolean,
    default: () => true,
  },
  name: {
    type: String,
    default: () => "新增",
  },
  fileList: {
    type: Array,
    default: () => [],
  },
});

// 文件移除
const fileRemove = (file) => {
  let [...temp] = props.fileList;
  temp.map((item, index) => {
    if (item.url == file.url) {
      temp.splice(index, 1);
    }
  });
  emit("fileRemove", temp);
};
//上传失败
const fileError = () => {
  Notification({
    title: "失败",
    message: "上传失败",
    type: "warning",
  });
};
console.log(props);
</script>
